<template>
  <!-- 添加或修改盘点计划对话框 -->
  <el-dialog :title="title" v-if="open" v-model="open" width="1200px" append-to-body class="dialog-box">
    <div class="tags">
      <div v-for="(tag, index) in tags" :key="index" :class="['tag', { active: index + 1 === active }]" @click="tabChange(item, index)">
        <div class="tag-num">{{ index + 1 }}</div>
        <div class="tag-name">{{ tag.name }}</div>
      </div>
    </div>
    <el-container class="container">
      <el-aside width="180px" class="eside">
        <div class="mark-box" :class="{ 'mark-detail': active === 3 }">
          <div class="mark">
            <img src="@/assets/images/mark_fff.svg" alt="" class="mark-icon" />
            <div>
              <span v-if="active === 1">基本信息</span>
              <span v-if="active === 2">商品价格</span>
              <span v-if="active === 3">详情描述</span>
            </div>
          </div>
          <div class="trangle"></div>
        </div>
        <div class="mark-box mark-spec" v-if="active === 1">
          <div class="mark">
            <img src="@/assets/images/mark_fff.svg" alt="" class="mark-icon" />
            <div>商品规格</div>
          </div>
          <div class="trangle"></div>
        </div>
        <div class="mark-box mark-unit" v-if="active === 1">
          <div class="mark">
            <img src="@/assets/images/mark_fff.svg" alt="" class="mark-icon" />
            <div>商品单位</div>
          </div>
          <div class="trangle"></div>
        </div>
      </el-aside>
      <el-main style="padding-left: 40px">
        <div v-show="active === 1">
          <el-form ref="form" :model="form" class="goods_add" :rules="rules" label-width="90px">
            <!-- <el-form-item label="商品条码:" prop="goodsSku">
              <el-input style="width: 400px;" ref="firstInput" v-model="form.goodsSku" placeholder="请输入条码"></el-input>
            </el-form-item> -->
            <el-form-item label="货号:" prop="itemNo">
              <div style="display: flex" :style="'width: 490px'">
                <el-input style="width: 400px" v-model="form.itemNo" :disabled="form.id"></el-input>
                <el-checkbox v-show="!form.id" v-model="form.autoItemNo" style="margin-left: 10px" label="1" @change="isAdd">自动递增</el-checkbox>
              </div>
              <!-- <el-input style="width: 400px;" v-else v-model="form.itemNo"
            :disabled="itemNoDisabled || !!form.id"></el-input> -->
            </el-form-item>
            <el-form-item label="商品名称:" prop="goodsName">
              <el-input ref="goodsName" style="width: 400px" v-model="form.goodsName"></el-input>
            </el-form-item>
            <el-form-item label="商品分类:" prop="classifyId">
              <el-tree-select
                v-model="form.classifyId"
                :data="categoryList"
                :props="{ value: 'id', label: 'classifyName', children: 'children' }"
                value-key="id"
                placeholder="选择产品分类"
                check-strictly
                style="width: 400px"
              />
            </el-form-item>
            <el-form-item label="计价方式:" prop="goodsPriceTypeDictValue">
              <el-select style="width: 400px" v-model="form.goodsPriceTypeDictValue" placeholder="请选择计价方式">
                <el-option v-for="item in goods_price_type" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <!-- 规格 -->
            <el-form-item label="是否多规格:" prop="enableSpec" style="margin-top: 60px">
              <el-switch v-model="form.enableSpec" :active-value="1" :inactive-value="0" @change="specSwicthChange"> </el-switch>
              <el-form-item v-if="form.enableSpec" style="margin-left: 150px" label="规格数量:" prop="specNumber">
                <el-select
                  style="margin-left: 10px; width: 200px"
                  v-model="form.specNumber"
                  value-key=""
                  placeholder="请选择规格数量"
                  filterable
                  @change="specNumChange"
                >
                  <el-option v-for="item in 3" :key="item" :label="item + '个'" :value="item"> </el-option>
                </el-select>
              </el-form-item>
            </el-form-item>

            <el-form-item label="商品规格:" prop="spec" v-if="!form.enableSpec">
              <el-input style="width: 400px" v-model="form.spec"></el-input>
            </el-form-item>
            <el-form-item label="商品规格:" v-if="form.enableSpec" required>
              <div>
                <div v-for="(item, index) in specGroupVoList" :key="index" class="mb10" style="display: flex">
                  <el-tree-select
                    style="width: 195px; margin-right: 5px"
                    default-expand-all
                    :props="{ value: 'id', label: 'specGroupName', children: 'children' }"
                    v-model="item.id"
                    :data="goodsSpecGroupList"
                    :render-after-expand="false"
                    @change="specGroupChange($event, index)"
                  />
                  <el-checkbox-group style="width: 195px; margin-right: 5px; display: flex" v-model="form[`spec${index + 1}`]" @change="specChange">
                    <el-checkbox :label="child.id" v-for="(child, idx) in specSelectList[index]" :key="idx">{{ child.specName }}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="批次管理:" prop="enableBatchNumber">
              <el-switch v-model="form.enableBatchNumber" active-value="1" inactive-value="0"> </el-switch>
            </el-form-item>
            <div style="display: flex">
              <el-form-item label="保质期管理:" prop="enableExpiry" style="width: 175px">
                <el-switch v-model="form.enableExpiry" active-value="1" inactive-value="0"> </el-switch>
              </el-form-item>
              <el-form-item label="保质期:" prop="expiryNum" style="width: 265px">
                <el-input
                  style="width: 400px"
                  v-model.number="form.expiryNum"
                  placeholder=""
                  @change="priceDataChange($event, 'expiryNum')"
                  clearable
                >
                  <template #append>天</template>
                </el-input>
              </el-form-item>
              <el-form-item label="提前:" prop="earlyWarningExpiry" style="width: 265px">
                <el-input
                  style="width: 400px"
                  v-model.number="form.earlyWarningExpiry"
                  placeholder=""
                  @change="priceDataChange($event, 'earlyWarningExpiry')"
                  clearable
                >
                  <template #append>天预警</template>
                </el-input>
              </el-form-item>
            </div>
            <div style="display: flex">
              <el-form-item label="消费周期:" prop="enablePeriodic" style="width: 175px">
                <el-switch v-model="form.enablePeriodic" active-value="1" inactive-value="0"> </el-switch>
              </el-form-item>
              <el-form-item label="消费周期:" prop="periodicNum" style="width: 265px">
                <el-input
                  style="width: 400px"
                  v-model.number="form.periodicNum"
                  placeholder=""
                  @change="priceDataChange($event, 'periodicNum')"
                  clearable
                >
                  <template #append>天</template>
                </el-input>
              </el-form-item>
              <el-form-item label="提前:" prop="periodicWarningExpiry" style="width: 265px">
                <el-input
                  style="width: 400px"
                  v-model.number="form.periodicWarningExpiry"
                  placeholder=""
                  @change="priceDataChange($event, 'periodicWarningExpiry')"
                  clearable
                >
                  <template #append>天预警</template>
                </el-input>
              </el-form-item>
            </div>

            <el-form-item label="商品品牌:" prop="brandId">
              <el-select style="width: 400px" v-model="form.brandId" placeholder="请选择" filterable>
                <el-option v-for="item in brandList" :key="item.id" :label="item.brandName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="商品图片:" class="goods_imgs">
              <el-upload
                class="avatar-uploader el-upload"
                :headers="headers"
                accept="image/*"
                :on-success="(res, file) => handleUploadSuccess(res, file, 'packImg')"
                :show-file-list="false"
                :action="uploadUrl"
              >
                <el-image v-if="form.packImg" class="avatar" :src="form.packImg" lazy>
                  <template #error>
                    <div class="image-slot">
                      <img class="avatar" src="@/assets/goods/order/img_failure.svg" alt="" />
                    </div>
                  </template>
                </el-image>
                <div v-else class="upload-text">点击上传主图</div>
                <div class="btn" v-if="form.packImg">
                  <el-button type="primary" @click.stop="deleteImg('packImg')">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </div>
              </el-upload>
              <el-upload
                class="avatar-uploader el-upload"
                :headers="headers"
                accept="image/*"
                :on-success="(res, file) => handleUploadSuccess(res, file, 'auxiliaryImg')"
                :show-file-list="false"
                :action="uploadUrl"
              >
                <el-image v-if="form.auxiliaryImg" class="avatar" :src="form.auxiliaryImg" lazy>
                  <template #error>
                    <div class="image-slot">
                      <img class="avatar" src="@/assets/goods/order/img_failure.svg" alt="" />
                    </div>
                  </template>
                </el-image>
                <div v-else class="upload-text">点击上传包装图</div>
                <div class="btn" v-if="form.auxiliaryImg">
                  <el-button type="text" @click.stop="deleteImg('auxiliaryImg')">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </div>
              </el-upload>
              <el-upload
                class="avatar-uploader el-upload"
                :headers="headers"
                accept="image/*"
                :on-success="(res, file) => handleUploadSuccess(res, file, 'primarilyImg')"
                :show-file-list="false"
                :on-error="handleError"
                :action="uploadUrl"
              >
                <el-image v-if="form.primarilyImg" class="avatar" :src="form.primarilyImg" lazy>
                  <template #error>
                    <div class="image-slot">
                      <img class="avatar" src="@/assets/goods/order/img_failure.svg" alt="" />
                    </div>
                  </template>
                </el-image>
                <div v-else class="upload-text">点击上传图片</div>
                <div class="btn" v-if="form.primarilyImg">
                  <el-button type="text" @click.stop="deleteImg('primarilyImg')">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="供货方式:" prop="supplyMode">
              <el-select style="width: 400px" v-model="form.supplyMode" placeholder="请选择">
                <el-option v-for="item in drop_shipping" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="默认供应商:" prop="supplierId">
              <el-select style="width: 400px" v-model="form.supplierId" placeholder="请选择" filterable>
                <el-option v-for="item in supplierList" :key="item.id" :label="item.supplierName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>

            <el-card class="box-card" shadow="never" style="margin-left: 90px; margin-top: 60px">
              <template #header>
                <div class="clearfix">
                  <span>商品单位</span>
                  <!-- <el-tag type="danger" style="margin-left: 10px;" size="normal" effect="dark"
                    v-for="(item, index) in unitRatios" :key="index">{{
                      item }}</el-tag> -->

                  <el-button type="danger" size="default" @click="handleAddUnit" style="float: right">
                    <el-icon>
                      <Plus></Plus>
                    </el-icon>
                  </el-button>
                </div>
              </template>
              <el-table v-loading="dialogLoading" :data="unitVoList" scrollbar-always-on>
                <el-table-column label="单位类型" align="center" width="150">
                  <template #default="scope">
                    <span v-if="scope.$index == 0">基本单位</span>
                    <span v-else>辅助单位{{ scope.$index }}</span>
                    <el-input v-show="false" v-model="scope.row.unitType"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单位名称" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.name" @change="unitListChange"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单位换算" align="center" width="300">
                  <template #default="scope">
                    <span v-if="scope.$index == 0">{{ scope.row.ratio }}</span>
                    <span v-else>
                      <el-input @change="unitListChange" v-model.number="scope.row.ratio" placeholder="" clearable>
                        <template #prepend>
                          <div>1{{ scope.row.name }}=</div>
                        </template>
                        <template #append>
                          <div v-if="unitVoList.length">
                            {{ unitVoList[0].name }}
                          </div>
                        </template>
                      </el-input>
                    </span>
                  </template>
                </el-table-column>
                <!-- <el-table-column label="默认单位" align="center">
                  <template #default="scope">
                    <el-switch v-model="scope.row.defaultFlag" :active-value="1" :inactive-value="0" />
                  </template>
                </el-table-column> -->
                <el-table-column label="出库默认" align="center">
                  <template #default="scope">
                    <el-switch
                      v-model="scope.row.defaultOutFlag"
                      :active-value="1"
                      :inactive-value="0"
                      @change="defaultChange($event, scope.$index, 'defaultOutFlag')"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="入库默认" align="center">
                  <template #default="scope">
                    <el-switch
                      v-model="scope.row.defaultInFlag"
                      :active-value="1"
                      :inactive-value="0"
                      @change="defaultChange($event, scope.$index, 'defaultInFlag')"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="盘点默认" align="center">
                  <template #default="scope">
                    <el-switch
                      v-model="scope.row.checkFlag"
                      :active-value="1"
                      :inactive-value="0"
                      @change="defaultChange($event, scope.$index, 'checkFlag')"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="单位条码" align="center" width="180">
                  <template #default="scope">
                    <el-input v-model="scope.row.code"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="允许销售" align="center">
                  <template #default="scope">
                    <el-checkbox true-label="0" false-label="1" v-model="scope.row.saleFlag">{{ false ? '允许' : '不允许' }}</el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80" align="center" fixed="right">
                  <template #default="scope">
                    <el-button type="text" @click="handleRemoveUnit(scope.$index)">
                      <el-icon>
                        <Delete></Delete>
                      </el-icon>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-form>
        </div>
        <el-card class="box-card mt20" shadow="never" v-show="active === 2">
          <template #header>
            <div class="clearfix">
              <span v-if="form.itemNo">商品货号：{{ form.itemNo }}</span>
              <span v-if="form.goodsName" style="margin-left: 20px">商品名称：{{ form.goodsName }}</span>
              <el-button style="float: right; margin-right: 10px" type="danger" @click="handleCustom">自定义价格</el-button>
            </div>
          </template>
          <el-table v-loading="dialogLoading" :data="priceVoList" scrollbar-always-on>
            <el-table-column label="单位名称" align="center" width="250">
              <template #default="scope">
                {{ scope.row.specIdsName }}
              </template>
            </el-table-column>
            <!-- 自定义区域 -->
            <el-table-column v-for="(col, index) in columns" :key="index" :label="col.title" align="center" :prop="col.dataIndex" :width="col.width">
              <template #default="scope">
                <el-input :disabled="col.disabled" v-model.number="scope.row[col.dataIndex]"></el-input>
              </template>
            </el-table-column>
            <!-- <el-table-column label="库存" align="center" width="150">
              <template #default="scope">
                <el-input v-model.number="scope.row.currentNumber"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="保质期" align="center" width="150">
              <template #default="scope">
                <el-input v-model.number="scope.row.expiryNum">
                  <template #append>天</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="提前预警" align="center" width="150">
              <template #default="scope">
                <el-input v-model.number="scope.row.earlyWarningExpiry">
                  <template #append>天</template>
                </el-input>
              </template>
            </el-table-column> -->
          </el-table>
        </el-card>

        <el-card class="box-card" shadow="always" v-show="active === 3">
          <template #header>
            <span>商品详情</span>
          </template>
          <editor v-model="form.goodsDetails" :min-height="192" />
        </el-card>
      </el-main>
    </el-container>
    <customPriceListForm ref="customPriceListForm" @change="customOk" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="up()" v-if="active > 1">上一步</el-button>
        <el-button type="primary" @click="next()" v-if="active < 3">下一步</el-button>
        <el-button type="primary" @click="submitForm(true)" v-if="active === 3">提交</el-button>
        <el-button type="primary" @click="submitForm(false)" v-if="active === 3 && !form.id">提交并继续</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import modelMixin from '@/mixins/modelMixin';
import request from '@/utils/request';
import { getBrandAllList } from '@/api/goods/brand';
import { getSupplierAllList } from '@/api/goods/supplier';
import { getToken } from '@/utils/auth';
import customPriceListForm from './customPriceListForm.vue';
import { refreshCache } from '@/api/goods/goods';
import goods from '@/api/goods/goods';
import { getDicts } from '@/api/system/dict/data/index';
import { globalHeaders } from '@/utils/request';
import { listGoodsSpec } from '@/api/goods/goodsSpec';
import { Fork } from '@icon-park/vue-next';
export default {
  name: 'addProductForm',
  dicts: ['drop_shipping'],
  mixins: [modelMixin],
  components: {
    // Editor,
    customPriceListForm
  },
  data() {
    return {
      uploadUrl: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload', // 上传的图片服务器地址
      fileList: [],
      headers: globalHeaders(),
      funcObj: goods,
      dropShipping: [],
      product: {
        name: '',
        price: '',
        description: ''
      },
      remark: '',
      img_loading: false,
      active: 1,
      open: false,
      itemNoDisabled: false,
      specGroupVoList: [], //规格数据
      specSelectList: [], //规格
      title: '添加产品',
      form: {
        spec1: [],
        spec2: [],
        spec3: []
      },
      rules: {
        goodsName: [{ required: true, message: '请输入商品名称', trigger: 'change' }],
        itemNo: [
          { required: true, message: '请输入商品货号', trigger: 'change' },
          { validator: this.checkAutoItemNo, trigger: 'change' }
        ],
        classifyId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        goodsUnit: [{ required: true, message: '请输入基本单位名称', trigger: 'change' }],
        barCode: [{ required: true, message: '请输入单位条码', trigger: 'change' }],
        goodsPriceTypeDictValue: [{ required: true, message: '请选择计价方式', trigger: 'change' }]
      },
      inputWidth: null,
      unitData: [], //单位数据
      specData: [], //单位数据
      warehouseList: [],
      dialogLoading: false,
      unitRatios: [], //单位换算
      unitVoList: [{}],
      priceVoList: [{}],
      locationArr: [],
      categoryList: [], //商品分类
      brandList: [], //商品品牌
      supplierList: [], //供应商
      drop_shipping: [], //支持代发
      goods_price_type: [],
      selectArr: [],
      selectedRows: [], //选择的行
      multiple: false,
      hasEdit: false,
      tags: [
        { name: '商品基础信息', complete: false },
        { name: '商品价格', complete: false },
        { name: '商品详情描述', complete: false }
      ],
      columns: [],
      disabled: false,
      isFirst: true,
      urls: {
        list: '/goods/category/allList'
      },
      columns1: [
        { title: '单位类型', dataIndex: 'type', align: 'center' },
        { title: '单位名称', dataIndex: 'name', align: 'center' },
        { title: '单位换算', dataIndex: 'g', align: 'center' },
        { title: '单位条码', dataIndex: 'barCode', align: 'center' },
        { title: '允许销售', dataIndex: 'isSale', align: 'center' }
      ]
    };
  },
  mounted() {
    // this.getDicts("mx_material_price");
    this.getGoodsSpecGroupAllList();
  },
  watch: {
    // 监听多规格，并生成价格表
    specSelectList: {
      handler: function (val) {
        console.log('666 :>> ', 666);
        let selectArr = [];
        val.forEach((list, index) => {
          selectArr.push(list.filter((item) => this.form[`spec${index + 1}`].includes(item.id)));
        });
        this.selectArr = selectArr;
        console.log('selectArr :>> ', selectArr);
      },
      immediate: true
    },
    // 监听多规格，并生成价格表
    unitVoList: {
      handler: function (val) {
        this.unitRatios = [];
        const def = val[0];
        for (let index = 1; index < val.length; index++) {
          this.unitRatios.push('1' + val[index].name + '=' + val[index].ratio + def.name);
        }
      },
      immediate: true
    },
    'form.enableSpec': {
      handler: function (val) {
        if (!val) {
          this.form.specNumber = undefined;
          this.specGroupVoList = [];
          this.specSelectList = [];
          // 对价格表清空后，并用单位表重新生成价格表
          this.unitListChange();
        }
      },
      immediate: true
    },
    form: {
      handler: function (val) {
        console.log('this.isFirst :>> ', this.isFirst);
        console.log('this.hasEdit :>> ', this.hasEdit);
        if (this.isFirst) {
          this.hasEdit = false;
          return;
        } else {
          console.log('this.hasEdit :>> ', '被改为true了');
          this.hasEdit = true;
        }
      },
      immediate: false,
      deep: true
    }
  },
  methods: {
    async add() {
      this.open = true;
      this.title = '添加产品';
      this.itemNoDisabled = false;
      let oldForm = JSON.parse(JSON.stringify(this.form));
      this.form = { autoItemNo: true, enablePeriodic: '0', goodsName: oldForm.goodsName };
      this.unitVoList = [{ ratio: 1 }];
      this.priceVoList = [{}];
      this.active = 1;
      this.initColumns();
      await this.getDicts(['drop_shipping', 'goods_price_type']);
      this.getCategoryAllList();
      this.getBrandAllList();
      this.getSupplierAllList();
      this.$nextTick(() => {
        this.$refs.goodsName.focus();
        this.$refs.form.clearValidate();
        this.isAdd(true);
      });
    },
    async edit(row) {
      this.open = true;
      this.isFirst = true;
      this.title = '编辑产品';
      await this.getDicts(['drop_shipping', 'goods_price_type']);
      this.form = JSON.parse(JSON.stringify(row));
      console.log('form :>> ', this.form);
      this.form.enableSpec = +this.form.enableSpec;
      this.priceVoList = this.form.priceVoList.map((item) => {
        // 循环item
        for (let key in item) {
          if (key.indexOf('Decimal') > -1) {
            item[key] = +item[key];
          }
        }
        (item.jzgCustomPriceVoList || []).forEach((val) => {
            item[val.name] = val.value;
        });
        if (!this.form.enableSpec) {
          item.specIdsName = item.specIds;
          console.log('999 :>> ', 999);
        }
        return item;
      });
      this.active = 1;
      this.form.accept = this.form.saleStatus == 1;
      this.rules.itemNo = [{ required: true, message: '请输入商品货号', trigger: 'change' }];
      this.itemNoDisabled = false;
      this.unitVoList = this.form.unitVoList;
      this.active = 1;
      this.initColumns();
      this.specNumChange(); // 规格数量
      // 生成价格表
      // this.specChange()
      // this.getShipping();
      this.getCategoryAllList();
      this.getBrandAllList();
      this.getSupplierAllList();
      // 对不同规格赋值
      for (let index = 0; index < this.form.specNumber; index++) {
        if (this.form.specGroupVoList && this.form.specGroupVoList.length > index) {
          this.form.specGroupVoList[index].goodsSpecVoList = this.form.specGroupVoList[index].goodsSpecVoList || [];
          this.form[`spec${index + 1}`] = this.form.specGroupVoList[index].goodsSpecVoList.filter((v) => v.checked === '1').map((item) => item.id);
          this.specGroupVoList[index].id = this.form.specGroupVoList[index].id;
          let item = this.defaultSpecGroupList.find((item) => item.id == this.form.specGroupVoList[index].id);
          console.log('item :>> ', item);
          this.specSelectList[index] = (item && item.goodsSpecVoList) || [];
          console.log('specSelectList :>> ', this.specSelectList);
        }
      }
      // 非多规格如果没有价格数据，初始化价格数据
      if (!this.form.enableSpec && this.priceVoList.length == 0) {
        this.unitListChange();
      }
      setTimeout(() => {
        this.isFirst = false;
        console.log('this.isFirst :>> ', this.isFirst);
      }, 5000);
    },
    addRow() {
      if (this.unitVoList.length == 0) {
        this.unitVoList.push({ ratio: 1 });
        return;
      }
      this.unitVoList.push({});
    },
    cancel() {
      if (this.hasEdit) {
        this.$modal
          .confirm('是否放弃保存当前商品信息', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            this.open = false;
          });
      } else {
        this.open = false;
      }
    },
    itemDelete(row, index) {
      this.unitVoList.splice(index, 1);
    },
    getListMatByCode(event, index) {
      const matCode = event.target.value;
      // Perform logic to get mat by code
    },
    getSpaceByWarehouseCode() {
      // Perform logic to get space by warehouse code
    },
    remoteMethod(query, row, index) {
      // Perform remote method logic here
    },
    locationChange(event, row, index) {
      // Handle location change logic here
    },
    uploadRequest() {
      // Perform upload request logic here
    },
    getDetail(url, id) {
      request({
        url: url + id,
        method: 'get'
      }).then((res) => {
        if (res.code == 200) {
          this.form = res.data;
        } else {
          this.$modal.msgError(res.msg);
        }
      });
    },
    next() {
      if (this.active === 1) {
        this.$refs.form.validate((bol) => {
          if (false) {
            throw new Error('商品信息填写不完整，请检查！');
          } else {
            this.tags[this.active].complete = true;
            if (this.active < 3) {
              this.active++;
            }
          }
        });
      } else {
        this.tags[this.active].complete = true;
        if (this.active < 3) {
          this.active++;
        }
      }
    },
    up() {
      this.active--;
    },
    tabChange(item, index) {
      this.active = index + 1;
    },
    initColumns() {
      getDicts('mx_material_price').then((res) => {
        this.columns = (res.data || []).map((item) => {
          return {
            title: item.dictLabel,
            dataIndex: item.dictValue,
            width: Math.max(item.dictLabel.length * 30, 150),
            align: 'center',
            sortable: true,
            disabled: ['behalfWholesaleDecimal', 'behalfPurchaseDecimal'].includes(item.dictValue)
          };
        });
      });
    },
    getShipping() {
      getDicts('drop_shipping').then((res) => {
        this.dropShipping = res.data;
      });
    },

    /** 转换部门数据结构 */
    normalizer(node) {
      return {
        id: node.id,
        label: node.classifyName,
        children: node.children
      };
    },
    // 查询所有品牌
    getBrandAllList() {
      getBrandAllList().then((res) => {
        this.brandList = res;
      });
    },
    // 查询所有供应商
    getSupplierAllList() {
      getSupplierAllList({ type: 0 }).then((res) => {
        this.supplierList = res;
      });
    },
    // 上传成功
    handleUploadSuccess(res, file, key) {
      // 如果上传成功
      if (res.code == 200) {
        this.form[key] = res.data.url;
      } else {
        this.$modal.msgError(res.msg);
      }
    },
    // 删除图片
    deleteImg(key) {
      this.form[key] = '';
    },
    handleCustom() {
      this.$refs.customPriceListForm.show();
    },
    customOk() {
      // 刷新redis缓存
      refreshCache()
        .then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess('刷新缓存成功');
            // 重新获取column
            this.initColumns();
          } else {
            this.$modal.msgError(res.msg);
          }
        })
        .catch((err) => {
          this.$modal.msgError('刷新缓存失败');
        });
    },
    isAdd(val) {
      if (val) {
        goods.getAutoItemNo().then((res) => {
          this.form.itemNo = res.data;
        });
      } else {
        this.form.itemNo = '';
      }
    },

    /**
     * @获取列表
     */
    getCategoryAllList() {
      const addKey = (treeData) => {
        return treeData.map((item) => ({
          ...item,
          disabled: item.children?.length > 0 ? true : false,
          children: item.children ? addKey(item.children) : []
        }));
      };
      var params = {
        url: '/order/goodsCategory/allList',
        method: 'get'
      };
      request(params).then((res) => {
        this.loading = false;
        var arr = res.filter((item) => item.classStatus == 1);
        this.categoryList = addKey(this.handleTree(arr, 'id'));
      });
    },
    classifyForm() {
      let params = { ...this.form };
      let specGroupVoList = JSON.parse(JSON.stringify(this.specGroupVoList));
      specGroupVoList.forEach((item, index) => {
        item.goodsSpecVoList = this.selectArr[index].map((item) => {
          return {
            id: item.id,
            specName: item.specName,
            checked: 1
          };
        });
      });
      console.log('params :>> ', params);
      params.specGroupVoList = specGroupVoList; //规格
      const defaultArr =  ['purchaseDecimal', 'behalfPurchaseDecimal', 'tradeDecimal', 'behalfWholesaleDecimal', 'wholesaleDecimal', 'commodityDecimal', 'vipDecimal']
      params.priceVoList = this.priceVoList.map(v => {
        console.log('v :>> ', v);
        // 处理自定义价格
        let customJsonArr = []
        for (let key in v) {
          if (!defaultArr.includes(key) && key.indexOf('customPrice') > -1 && key != 'customPriceJson') {
            customJsonArr.push({
              name: key,
              value: v[key]
             })
          }
        }
        v.customPriceJson = JSON.stringify(customJsonArr)
        return v
      }); //价格
      // params.periodicNum ?  params.periodicNum : 0 //消费周期
      // params.periodicWarningExpiry ? params.periodicWarningExpiry : 0 //预警天数
      params.unitVoList = this.unitVoList.map((v, idx) => ((v.unitType = idx + 1), v)); //单位
      return params;
    },

    getPrice(row, child) {
      let defaultPriceArr = ['unitName', 'costPrice', 'purchasePrice', 'wholesalePrice', 'salePrice', 'upsetPrice', 'retailPrice'];
      if (defaultPriceArr.includes(child.dictValue)) {
        return row[child.dictValue];
      } else {
        let item = (row.goodsRedisList || []).find((item) => item.priceName == child.dictValue);
        return item ? item.price : '';
      }
    },
    handleAddSpec() {
      this.specData.push({});
    },
    specNumChange() {
      this.specGroupVoList = [];
      Object.assign(this.form, { spec1: [], spec2: [], spec3: [] });
      this.specSelectList = [];
      for (let index = 0; index < this.form.specNumber; index++) {
        this.specGroupVoList.push({ id: '', specId: '' });
        this.specSelectList.push([]);
      }
    },
    specSwicthChange(v) {
      if (v) {
        this.specGroupVoList = [];
        this.specSelectList = [];
        this.form.specNumber = 1;
        for (let index = 0; index < 1; index++) {
          this.specGroupVoList.push({ id: '', specId: '' });
          this.specSelectList.push([]);
        }
      } else {
        this.form.specNumber = undefined;
        this.specGroupVoList = [];
        this.specSelectList = [];
        this.form.spec = '';
      }
    },
    // 通过规格分类id查询规格值
    specGroupChange(value, index) {
      listGoodsSpec({ specGroupId: value }).then((res) => {
        this.specSelectList[index] = res.rows;
        console.log('this.specSelectList :>> ', this.specSelectList);
      });
    },
    specChange(v) {
      console.log(this.form, 'form');
      let selectArr = [];
      this.specSelectList.forEach((list, index) => {
        selectArr.push(list.filter((item) => this.form[`spec${index + 1}`].includes(item.id)));
      });
      // 已选择的规格信息
      this.selectArr = selectArr;
      console.log('selectArr :>> ', selectArr);
      // 生成规格价格表，包括规格id用逗号拼接，规格名称用-拼接，多规格混合
      let priceVoList = [];
      let selectArr1 = selectArr[0] || [];
      let selectArr2 = selectArr[1] || [];
      let selectArr3 = selectArr[2] || [];
      selectArr1.forEach((item1) => {
        selectArr2.forEach((item2) => {
          selectArr3.forEach((item3) => {
            priceVoList.push({
              specIds: [item1.id, item2.id, item3.id].join(','),
              specIdsName: [item1.specName, item2.specName, item3.specName].join('-')
            });
          });
          if (selectArr3.length == 0) {
            priceVoList.push({
              specIds: [item1.id, item2.id].join(','),
              specIdsName: [item1.specName, item2.specName].join('-')
            });
          }
        });
        if (selectArr2.length == 0) {
          priceVoList.push({
            specIds: [item1.id].join(','),
            specIdsName: [item1.specName].join('-')
          });
        }
      });
      this.priceVoList = priceVoList;
      console.log('priceVoList :>> ', this.priceVoList);
    },
    handleAddUnit() {
      // 最多三个单位
      if (this.unitVoList.length > 3) {
        this.$modal.msgError('最多添加三个单位');
        return;
      }
      this.unitVoList.push({});
    },
    defaultChange(v, index, key) {
      this.unitVoList.forEach((item, i) => {
        if (i == index) {
          item[key] = v ? 1 : 0;
        } else {
          item[key] = 0;
        }
      });
    },
    // 根据保质期和提前预警时间改变价格表
    priceDataChange(v, key) {
      this.priceVoList.forEach((item) => {
        item[key] = v;
      });
    },
    unitListChange() {
      console.log('777 :>> ', 777);
      this.unitRatios = [];
      const def = this.unitVoList[0];
      for (let index = 1; index < this.unitVoList.length; index++) {
        if (this.unitVoList[index].name && this.unitVoList[index].ratio) {
          this.unitRatios.push('1' + this.unitVoList[index].name + '=' + this.unitVoList[index].ratio + def.name);
        }
      }
      // 但规格需要用单位表生成价格表
      if (!this.form.enableSpec) {
        this.priceVoList = [];
        this.unitVoList.forEach((item, i) => {
          if (item.name) {
            this.priceVoList.push({
              specIds: item.name,
              specIdsName: item.name
            });
          }
        });
        console.log('this.priceVoList :>> ', this.priceVoList);
      }
    },
    handleRemoveUnit(index) {
      this.unitVoList.splice(index, 1);
    },

    // 校验商品货号是否存在
    checkAutoItemNo(rule, value, callback) {
      let params = {
        itemNo: this.form.itemNo,
        id: this.form.id
      };
      goods.checkAutoItemNo(params).then((res) => {
        let flag = res.data;
        if (flag) {
          callback(new Error('编号已存在'));
        } else {
          callback();
        }
      });
    },
    validateSpec() {
      let flag = true;
      this.priceVoList.forEach((item) => {
        if (!item.specIds) {
          flag = false;
        }
      });
      return this.priceVoList.length && flag;
    },
    /**
     * @提交
     * @param {*} close
     */
    submitForm(close = true) {
      if (this.form.enableSpec && !this.validateSpec()) {
        this.$modal.msgError('请填写完整规格信息');
        return;
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          let params = this.classifyForm();
          this.loading = true;
          if (this.form.id) {
            this.funcObj
              .update(params)
              .then((res) => {
                this.loading = false;
                if (res.code == 200) {
                  this.$modal.msgSuccess('操作成功');
                  if (close) {
                    this.open = false;
                  }
                  this.$emit('ok');
                } else {
                  this.$modal.msgError(res.msg);
                }
              })
              .catch((err) => {
                this.loading = false;
                console.log('err :>> ', err);
              });
          } else {
            this.funcObj
              .add(params)
              .then((res) => {
                this.loading = false;
                if (res.code == 200) {
                  this.$modal.msgSuccess('新增成功');
                  if (close) {
                    this.open = false;
                  } else {
                    console.log('777 :>> ', 777);
                    this.add();
                  }
                  this.$emit('ok');
                } else {
                  this.$modal.msgError(res.msg);
                }
              })
              .catch((err) => {
                console.log('err :>> ', err);
                this.loading = false;
              });
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.tags {
  width: 80%;
  margin: 0 auto;
}

.tags,
.tag {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  cursor: pointer;
}

.tag-num {
  margin-right: 10px;
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background-color: #ff9d93;
  text-align: center;
  color: #fff;
  line-height: 40px;
  font-size: 20px;
}

.tag-name {
  height: 40px;
  line-height: 40px;
  font-size: 20px;
}

.avatar-uploader,
.el-upload {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px !important;
  height: 178px;
  display: inline-block;
  margin-right: 10px;
}

.avatar-uploader:hover,
.el-upload:hover {
  border-color: #409eff;
}

.imgs {
  display: inline-block;
}

.avatar-uploader__img {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px !important;
  height: 178px;
  display: inline-block;
  margin-right: 10px;

  img {
    width: 178px !important;
    height: 178px;
    object-fit: fill;
  }
}

.btn {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  width: 178px !important;
  height: 178px;
  border-radius: 0 6px 0 6px;
  text-align: center;
  line-height: 178px;
}

.avatar-uploader:hover {
  // 鼠标悬浮显示按钮
  .btn {
    display: block;
  }
}

.upload-text {
  font-size: 14px;
  color: #8c939d;
  line-height: 178px;
  text-align: center;
  margin: 0 auto;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.active .tag-num {
  background-color: #ff4d3c;
}

.container {
  border: 1px solid #ebeef5;
}

.eside {
  background-color: #fff;
  border-right: 1px solid #ebeef5;
  margin-bottom: 0 !important;
  padding: 0 !important;
  position: relative;
  overflow: unset !important;
}

.left {
  width: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.mark {
  width: 180px;
  background-color: #1569e8;
  height: 50px;
  display: flex;
  font-size: 28px;
  color: #fff;
  align-items: center;
  padding-left: 10px;
  /* display: none; */
}

.mark div {
  margin-bottom: 2px;
}

.mark-box {
  display: flex;
  align-items: center;
  position: absolute;
  top: 40px;
}

.mark-spec {
  top: 250px;

  .mark {
    background: #a90fee;
  }

  .trangle {
    border-left: 25px solid #a90fee;
  }
}

.mark-unit {
  top: 850px;

  .mark {
    background: #1bb02b;
  }

  .trangle {
    border-left: 25px solid #1bb02b;
  }
}

.mark-detail {
  .mark {
    background: #ee0fb5;
  }

  .trangle {
    border-left: 25px solid #ee0fb5;
  }
}

/* 箭头向右，高度50 */
.trangle {
  width: 0;
  height: 0;
  border-top: 25px solid transparent;
  border-left: 25px solid #1569e8;
  border-bottom: 25px solid transparent;
  left: 180px;
}

.mark-icon {
  width: 36px;
}
</style>
<style type="text/css">
.goods_add .el-form-item .el-form-item__content {
  width: 400px !important;
}

.goods_imgs.el-form-item .el-form-item__content {
  width: 100% !important;
}

.unit-list.el-form-item {
  margin-bottom: 0 !important;
}

.unit-list.el-form-item .el-form-item__content {
  margin-left: 0 !important;
  width: auto !important;
}

.goods_add .el-upload {
  display: block !important;
}
</style>
<style type="text/css">
.dialog-box .el-dialog__body {
  min-height: 600px;
}
</style>